<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索于添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
          <!-- 添加用户的对话框 -->
          <el-dialog
            title="添加用户"
            :visible.sync="addDialogVisible"
            width="50%"
            @closed="addDialogClosed"
          >
            <!-- 内容主题区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile">
                <el-input v-model="addForm.mobile"></el-input>
              </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
              <el-button @click="addDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <template>
        <el-table :data="userList" style="width: 100%" border stripe>
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column prop="username" label="姓名" width="180"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChanged(scope.row)"
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="modifyUser(scope.row.id)"
              ></el-button>

              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUserInfo(scope.row.id)"
              ></el-button>
              <el-tooltip
                type="danger"
                content="分配角色"
                icon="el-icon-delete"
                size="mini"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="success"
                  icon="el-icon-setting"
                  size="mini"
                  @click="setRole(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 页码区域 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.queryInfo.pagenum"
          :page-sizes="[1,2,5,10]"
          :page-size="this.queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="this.total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 修改用户信息的对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="modifyDialog" width="50%" @close="modifyDialogClosed">
      <!-- 内容主题区域 -->
      <el-form :model="modifyForm" :rules="addFormRules" ref="modifyFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="modifyForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="modifyForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="modifyForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyDialog = false">取 消</el-button>
        <el-button type="primary" @click="modifyUserSure">确 定</el-button>
      </span>
    </el-dialog>
    <!--  分配角色对话框-->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%">
      <p>当前的用户：{{userInfo.username}}</p>
      <p></p>
      <p>当前的角色:{{userInfo.role_name}}</p>
      <p>
        分配新的角色:
        <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data: () => {
    // 验证邮箱的校验规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则
      // eslint-disable-next-line no-useless-escape
      var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }

      if (!reg.test(value)) {
        return callback(new Error('邮箱格式不正确'))
      }
      callback()
    }
    // 手机号的验证规则
    var checkMobile = (rule, value, callback) => {
      // 校验规则
      var reg = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
      if (!value) {
        return callback(new Error('手机号不能为空'))
      }
      if (!reg.test(value)) {
        return callback(new Error('手机格式不正确'))
      }
      callback()
    }
    return {
      swithValue: true,
      // 获取用户列表的参数对象
      // queryInfo 中的query就是为提供搜索时提供的
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      modifyDialog: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户的表单规则对象
      addFormRules: {
        userName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在3~10个字符', trigger: 'blur' }
        ],
        passWord: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在6~12个字符', trigger: 'blur' }
        ],
        email: [{ validator: checkEmail, trigger: 'blur' }],
        mobile: [{ validator: checkMobile, trigger: 'blur' }]
      },
      // 修改用户信息数据 更改之前保存
      modifyForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 保存获取分配角色中的信息
      rolesList: [],
      // 分配角色下拉框使用
      selectRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList () {
      // console.log('yes')
      const {
        data: { data, meta }
      } = await this.$http.get('/users', { params: this.queryInfo })
      if (meta.status !== 200) return this.$message.error(meta.status)
      this.userList = data.users
      this.total = data.total
      // console.log(data)
      // console.log(this.userList)
      // console.log(this.total)
    },
    // 监听swith 状态开关的显示
    async userStateChanged (row) {
      // console.log(row)
      const {
        data: { meta }
      } = await this.$http.put(`/users/${row.id}/state/${row.mg_state}`)
      // console.log(data, meta)

      // 修改状态失败需要提示用户 把状态重置回去
      if (meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error('修改状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 页码区域的函数
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.queryInfo.pagesize = val
      // 重新获取用户列表的数据
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 添加用户弹出框关闭后  重置表单的内容
    addDialogClosed () {
      // this.$refs[addFormRef].resetFields()
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户弹出框确认后 验证整个表单数据 并把数据存到数据库
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 表单通过验证
        const {
          data: { meta }
        } = await this.$http.post('/users', this.addForm)
        // console.log(data, meta)
        if (meta.status !== 201) return this.$message.error(meta.msg)
        this.$message.success('添加用户成功')
        // 添加成功后隐藏对话框
        this.addDialogVisible = false
        // 添加用户成功后重新请求下用户列表
        this.getUserList()
      })
    },
    // 根据id查询要编辑的用户信息 保存修改的用户信息 展示编辑用户的对话框
    async modifyUser (id) {
      this.modifyDialog = true
      const {
        data: { data, meta }
      } = await this.$http.get(`/users/${id}`)
      // console.log(data, meta)
      if (meta.status !== 200) return this.$message.error('获取用户信息失败')
      // 把数据存起来以便展示在页面
      this.modifyForm = data
    },
    // 监听修改用户的对话框关闭事件
    modifyDialogClosed () {
      this.$refs.modifyFormRef.resetFields()
    },
    // 修改用户信息，把数据提交到数据库
    modifyUserSure () {
      this.$refs.modifyFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        const {
          data: { meta }
        } = await this.$http.put(`/users/${this.modifyForm.id}`, {
          email: this.modifyForm.email,
          mobile: this.modifyForm.mobile
        })
        // console.log(data, meta)
        if (meta.status !== 200) return this.$message.error('修改用户信息失败')
        // 提示修改数据成功
        this.$message.success('修改用户信息成功')
        // 隐藏对话框
        this.modifyDialog = false
        // 重新获取用户列表信息
        this.getUserList()
      })
    },
    // 根据id删除用户信息
    deleteUserInfo (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          console.log(id)
          const {
            data: { meta }
          } = await this.$http.delete(`users/${id}`)
          // console.log(data, meta)
          if (meta.status !== 200) return this.$message.error(meta.status.msg)
          // 提示显出成功
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 重新获取页面上面的数据
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配角色处理函数
    async setRole (userInfo) {
      // 弹出对话框之前获取所有的角色
      const {
        data: { data, meta }
      } = await this.$http.get('/roles')
      // console.log(res)
      if (meta.status !== 200) { return this.$message.error('获取用户角色列表失败') }
      // 保存数据
      this.rolesList = data
      // 显示对话框
      this.setRoleDialogVisible = true
      // console.log(userInfo)
      // 保存传递过来的信息
      this.userInfo = userInfo
    },
    // 分配角色 ,后台保存数据
    async saveRole () {
      if (!this.selectRoleId) return this.$message.error('请选中需要分配角色的选项')
      const { data: { meta } } = await this.$http.put(`/users/${this.userInfo.id}/role`, { rid: this.selectRoleId })
      if (meta.status !== 200) { return this.$message.error(meta.msg) }
      //  console.log(data, meta)
      // 提示用户分配角色成功
      this.$message.success(meta.msg)
      // 重置selectRoleId userInfo
      this.selectRoleId = ''
      this.userInfo = ''
      // 关闭对话框
      this.setRoleDialogVisible = false
      // 重新获取页面的数据
      this.getUserList()
    }
  }
}
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 20px;
  font-size: 12px;
}
</style>
